package com.wondertek.mist.gallery;


import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.wondertek.mist.plugins.GalleryPlugin;
import com.wondertek.mist.utils.RUtil;

public class ImageGallery extends Activity {

	private Bitmap defaultImage;
	private ViewPager viewPager;
	private TextView viewPageCount;
	private Button backButton;
	private DisplayImageOptions options;
	protected ImageLoader imageLoader = ImageLoader.getInstance();

	private String[] sampleImages = {
			"http://attach.bbs.miui.com/forum/month_1012/1012021239abb4059c16f58442.jpg",
			"http://www.qipaox.com/tupian/20091/20091822192.jpg",
			"http://image11.m1905.cn/uploadfile/2008/0924/19153127332.jpg",
			"http://sh.suijue.com/picture/1/1029/6.jpg",
			"http://attach.bbs.miui.com/forum/201111/15/184914onpr6a33shjo3jvt.jpg",
			"http://img.article.pchome.net/00/26/80/13/pic_lib/wm/20070706_24c538b0a0971bfe2881MEjkwy0SBFuN.jpg",
			"http://attach.bbs.miui.com/forum/201111/15/184851m2cl8dfnddcrtcdt.jpg",
			"http://pic.zhutou.com/html/UploadPic/2010-7/2010783933760.jpg"};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Bundle bundle = getIntent().getExtras();
		String image = bundle.getString(GalleryPlugin.MIST_PHOTO_EXTRA);
		if(image!=null) {
			try {
				JSONArray imageArray = new JSONArray(image);
				sampleImages = new String[imageArray.length()];
				for(int i=0;i<imageArray.length();i++) {
					sampleImages[i] = imageArray.getString(i);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		defaultImage = BitmapFactory.decodeResource(getResources(),RUtil.drawable(this,"ic_launcher"));
		imageLoader.init(ImageLoaderConfiguration.createDefault(ImageGallery.this));

		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(RUtil.drawable(this,"gallery_empty"))
				.showImageOnFail(RUtil.drawable(this,"gallery_error")).resetViewBeforeLoading()
				.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new FadeInBitmapDisplayer(300)).build();

		setContentView(RUtil.layout(this,"gallery_pageview"));
		backButton = (Button) findViewById(RUtil.id(this,"btnback"));
		backButton.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				ImageGallery.this.onBackPressed();
				ImageGallery.this.finish();
			}
		});
		
		SamplePagerAdapter adapter = new SamplePagerAdapter();
		viewPageCount = (TextView) findViewById(RUtil.id(this,"txtcount"));
		viewPageCount.setText("1/" + String.valueOf(sampleImages.length));
		try {
			viewPager = (HackyViewPager) findViewById(RUtil.id(this,"pager"));
			if(adapter!=null) {
				viewPager.setAdapter(adapter);
			}
			viewPager.setOnPageChangeListener(new OnPageChangeListener() {
				// 页面更变
				public void onPageSelected(int position) {
					viewPageCount.setText(String.valueOf(position + 1) + "/"
							+ String.valueOf(sampleImages.length));
				}

				public void onPageScrollStateChanged(int state) {
				}

				public void onPageScrolled(int position, float positionOffset,
						int positionOffsetPixels) {
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	class SamplePagerAdapter extends PagerAdapter {
		private LayoutInflater inflater;

		SamplePagerAdapter() {
			inflater = getLayoutInflater();
		}

		public int getCount() {
			return sampleImages.length;
		}

		public View instantiateItem(ViewGroup container, int position) {
			View imageLayout = inflater.inflate(RUtil.layout(container.getContext(),"gallery_imageshow"),container, false);
			final PhotoView photoView = (PhotoView) imageLayout.findViewById(RUtil.id(container.getContext(),"image"));
			final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(RUtil.id(container.getContext(),"loading"));

			final String imgUrl = sampleImages[position];
			imageLoader.displayImage(imgUrl, photoView, options,
					new SimpleImageLoadingListener() {
						public void onLoadingStarted(String imageUri, View view) {
							spinner.setVisibility(View.VISIBLE);
						}

						public void onLoadingFailed(String imageUri, View view,FailReason failReason) {
							String message = null;
							switch (failReason.getType()) {
							case IO_ERROR:
								message = "获取图片类型错误！";
								break;
							case DECODING_ERROR:
								message = "影像解码错误！";
								break;
							case NETWORK_DENIED:
								message = "网络状况不佳";
								break;
							case OUT_OF_MEMORY:
								message = "内存不足";
								break;
							case UNKNOWN:
								message = "未知错误";
								break;
							}
							Toast.makeText(ImageGallery.this, message,Toast.LENGTH_SHORT).show();
							spinner.setVisibility(View.GONE);
						}

						public void onLoadingComplete(String imageUri,View view, Bitmap loadedImage) {
							spinner.setVisibility(View.GONE);
						}
					});
			((ViewPager) container).addView(imageLayout, 0);
			return imageLayout;
		}

		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

	}
}
